package com.example.ccj.b.c.draw;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.ccj.u.ImageUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.ScreenUtils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 分数绘制
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/5/22 23:27
 */
public class DrawFenShuView extends View {
    //中间线段两边偏移距离
    int linePadding = 10;
    //线段高度
    float lineHeight = 5;
    float startPadding = 10;
    //开始绘制位置
    float startX = startPadding;
    //中间分割线和数字之间的距离
    int lineAndNumberDistance = 20;
    //运算符号放大比例 倍数关系 0.3指比文字大0.3倍
    double signAmplifyProportion = 0.3;

    float endX;
    float endY;
    //是否绘制结果
    boolean isDrawResult = true;
    //结果分子
    int resultFenZi;
    //结果分母
    int resultFenMu;

    //默认字体大小
    float size = 30;
    Paint paint;

    FenShu[] fenShuList = new FenShu[]{new FenShu(822,25000,true),new FenShu(52,75,false)};

    public DrawFenShuView(Context context, FenShu[] fenShuList, int size, boolean isDrawResult) {
        super(context);
        this.fenShuList = fenShuList;
        this.isDrawResult = isDrawResult;
        //dp转换px
        this.size = dp2px(size);
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(this.size);
        paint.setStrokeWidth(lineHeight);//线条宽度
        readableText = new StringBuilder();
    }

    public DrawFenShuView(Context context, FenShu[] fenShuList, int size) {
        super(context);
        this.fenShuList = fenShuList;
        //dp转换px
        this.size = dp2px(size);
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(this.size);
        paint.setStrokeWidth(lineHeight);//线条宽度
        readableText = new StringBuilder();
    }

    public DrawFenShuView(Context context, FenShu fenShu, int size) {
        super(context);
        fenShuList = new FenShu[] {fenShu};
        //dp转换px
        this.size = dp2px(size);
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(this.size);
        paint.setStrokeWidth(lineHeight);//线条宽度
        readableText = new StringBuilder();
    }

    public DrawFenShuView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //dp转换px
        this.size = dp2px(size);
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(this.size);
        paint.setStrokeWidth(lineHeight);//线条宽度
        readableText = new StringBuilder();
    }

    /**
     * 获取可读分数文本
     * @return 文本
     */
    public String getReadableText(){
        return readableText.toString();
    }

    //可读文本
    private final StringBuilder readableText;

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        if (fenShuList.length < 1) return;
        startX = startPadding;
//        LogUtils.d("startX:" + startX);
        for (int i = 0; i < fenShuList.length; i++) {
            paint.setColor(fenShuList[i].color);
            readableText.append(fenShuList[i].fenMu).append("分之").append(fenShuList[i].fenZi);
            drawFenShu(String.valueOf(fenShuList[i].fenZi),String.valueOf(fenShuList[i].fenMu),canvas);
            if (fenShuList.length > 1) {
                if (i<fenShuList.length -1) {
                    if (fenShuList[i].isJiaFa) {
                        readableText.append("加上");
                        paint.setColor(Color.BLUE);
                        drawYunSuanFuHao(0,canvas);
                    } else {
                        readableText.append("减去");
                        paint.setColor(Color.RED);
                        drawYunSuanFuHao(1,canvas);
                    }
                } else {
                    //最后一个数据画等号
                    if (isDrawResult) {
                        readableText.append("等于多少？");
                        drawYunSuanFuHao(2,canvas);
                    }
                }
            }
        }

        //画结果
        if (isDrawResult) {
            if (resultFenZi > 0 || resultFenMu > 0) {
                paint.setColor(Color.rgb(223,104,0));
                String fenzi = "";
                if (resultFenZi > 0) fenzi = String.valueOf(resultFenZi);
                String fenmu = "";
                if (resultFenMu > 0) fenmu = String.valueOf(resultFenMu);
                drawFenShu(fenzi,fenmu,canvas);
            }
        }
    }

    private void drawFenShu(String fenzi,String fenmu, Canvas canvas){

        startX = startX + linePadding;
        //单行文本高度
        //Y的起始坐标
        float startY = size;
        //分子宽度
        float fenZiWidth = paint.measureText(fenzi);
        //分母宽度
        float fenMuWidth = paint.measureText(fenmu);
        //获取最大文字宽度
        float max = Math.max(fenZiWidth,fenMuWidth);
        //求出居中位置需要的偏移量
        float v = Math.abs(fenZiWidth - fenMuWidth) / 2;

        float fenZiY = startY;
        float lineY = (float) (size * 2 + lineAndNumberDistance * 2) /2 - lineHeight/2;
        endY = size * 2 +lineAndNumberDistance;

        //画出分子
        float fenZiX = max == fenZiWidth ? startX: startX + v;
        canvas.drawText(fenzi, fenZiX,fenZiY,paint);

        //画出中间分割线
        float lineStartX = startX-linePadding;
        endX = startX+linePadding+max;
        //超出范围减小字体大小重绘
        if (endX > ScreenUtils.getAppScreenWidth()) {
            LogUtils.d("超出范围减小字体大小重绘:"+size);
            size = size-(int)((double)size*0.1);
            LogUtils.d("运算符号超出范围减小字体大小重绘减去后:" + size);
            invalidate();//重绘
            return;
        } else {

        }
        canvas.drawLine(lineStartX,lineY,endX,lineY,paint);

        //画出分母
        float fenMuX = max == fenMuWidth ? startX : startX + v;
        canvas.drawText(fenmu, fenMuX,endY,paint);
    }

    private void drawYunSuanFuHao(int type,Canvas canvas){
        //画出运算符号
        float yunSuanFuHaoY  = endY / 2 + size/2;

        startX = endX;
        paint.setTextSize(size + (float) ((double)size*signAmplifyProportion));
        String yunSuanFu = "";
        if (type == 0) yunSuanFu = " + ";
        if (type == 1) yunSuanFu = " - ";
        if (type == 2) yunSuanFu = " = ";

        canvas.drawText(yunSuanFu, startX,yunSuanFuHaoY,paint);
        startX += paint.measureText(yunSuanFu);
        endX = startX;

        //超出范围减小字体大小重绘
        if (startX > ScreenUtils.getAppScreenWidth()) {
            LogUtils.d("运算符号超出范围减小字体大小重绘:" + size);
            size = size-(int)((double)size*0.1);
            LogUtils.d("运算符号超出范围减小字体大小重绘减去后:" + size);
            invalidate();//重绘
            return;
        }
        paint.setTextSize(size);
    }

    int width = 0;
    int height = 0;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        width = measureWidth(widthMeasureSpec);
        height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    private int measureHeight(int measureSpec) {
        float result = 0;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        if (mode == MeasureSpec.EXACTLY) {
            result = size;
        } else {
            result=this.size*2+lineAndNumberDistance*2+5;
            if (mode == MeasureSpec.AT_MOST) {
                result = Math.min(result, size);
            }
        }
        return (int)result;
    }

    private int measureWidth(int measureSpec) {
        float result = 0;
        int mode = MeasureSpec.getMode(measureSpec);
        int size2 = MeasureSpec.getSize(measureSpec);

        if (mode == MeasureSpec.EXACTLY) {
            result = size2;
        } else {
//            result = size2;
            //开始位置的偏移距离
            result += startPadding;
            paint.setTextSize(size);
            //分数的宽度
            for (FenShu fenShu : fenShuList) {
                float fenZiWidth = paint.measureText(String.valueOf(fenShu.fenZi));
                //分母宽度
                float fenMuWidth = paint.measureText(String.valueOf(fenShu.fenMu));
                result += Math.max(fenZiWidth,fenMuWidth);
                result += linePadding * 2;
            }

            //加上结果
            if (isDrawResult) {
                if (resultFenZi > 0 || resultFenMu > 0) {
                    float fenZiWidth = paint.measureText(String.valueOf(resultFenZi));
                    float fenMuWidth = paint.measureText(String.valueOf(resultFenMu));
                    result += Math.max(fenZiWidth,fenMuWidth);
                    result += linePadding * 2;
                }
            }

            //符号的宽度
            if (fenShuList.length > 1) {
                float v = size;
                double vvv = size*signAmplifyProportion;
                v += (float) vvv;
                paint.setTextSize(v);
                v = paint.measureText(" - ");
                result += v * (fenShuList.length);
                paint.setTextSize(size);
            }

            if (mode == MeasureSpec.AT_MOST) {
                result = Math.min(result, size2);
            }
        }
        return (int)result;
    }


    private int getWeight(){
        float result = 0;
        result += startPadding;
        paint.setTextSize(size);
        //分数的宽度
        for (FenShu fenShu : fenShuList) {
            float fenZiWidth = paint.measureText(String.valueOf(fenShu.fenZi));
            //分母宽度
            float fenMuWidth = paint.measureText(String.valueOf(fenShu.fenMu));
            result += Math.max(fenZiWidth,fenMuWidth);
            result += linePadding * 2;
        }

        //加上结果
        if (isDrawResult) {
            if (resultFenZi > 0 || resultFenMu > 0) {
                float fenZiWidth = paint.measureText(String.valueOf(resultFenZi));
                float fenMuWidth = paint.measureText(String.valueOf(resultFenMu));
                result += Math.max(fenZiWidth,fenMuWidth);
                result += linePadding * 2;
            }
        }

        //符号的宽度
        if (fenShuList.length > 1) {
            float v = size;
            double vvv = size*signAmplifyProportion;
            v += (float) vvv;
            paint.setTextSize(v);
            v = paint.measureText(" - ");
            result += v * (fenShuList.length);
            paint.setTextSize(size);
        }
        return (int) result;
    }

    public Bitmap getBitmap(){
        Bitmap bitmap = ImageUtils.loadBitmapFromView(this);
        int w = bitmap.getWidth() < getWeight() ? bitmap.getWidth():getWeight();
        return Bitmap.createBitmap(bitmap,0,0,w,height);
    }

    /**
     * 保存签名位图到文件
     * @param filename 文件名
     * @return 是否保存成功
     */
    public boolean saveSignatureToFile(String filename) {
        Bitmap bitmap = getBitmap();
        try {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(filename));
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    public int getResultFenZi() {
        return resultFenZi;
    }

    public void setResultFenZi(int resultFenZi) {
        this.resultFenZi = resultFenZi;
        if (isDrawResult) requestLayout();//重绘
    }

    public int getResultFenMu() {
        return resultFenMu;
    }

    public void setResultFenMu(int resultFenMu) {
        this.resultFenMu = resultFenMu;
        if (isDrawResult) requestLayout();//重绘
    }

    public int getLinePadding() {
        return linePadding;
    }

    public void setLinePadding(int linePadding) {
        this.linePadding = linePadding;
    }

    public float getLineHeight() {
        return lineHeight;
    }

    public void setLineHeight(float lineHeight) {
        this.lineHeight = lineHeight;
    }

    public float getStartX() {
        return startPadding;
    }

    public void setStartX(float startX) {
        this.startPadding = startX;
    }

    public FenShu[] getFenShuList() {
        return fenShuList;
    }

    public void setFenShuList(FenShu[] fenShuList,int size) {
        LogUtils.d("设置参数");
        this.fenShuList = fenShuList;
        this.size = dp2px(size);
        paint.setTextSize(this.size);
//        requestLayout();
    }

    public void setFenShuList(FenShu[] fenShuList, int size, boolean isDrawResult) {
        this.fenShuList = fenShuList;
        this.isDrawResult = isDrawResult;
        this.size = dp2px(size);
        paint.setTextSize(this.size);
    }

    public int getLineAndNumberDistance() {
        return lineAndNumberDistance;
    }

    public void setLineAndNumberDistance(int lineAndNumberDistance) {
        this.lineAndNumberDistance = lineAndNumberDistance;
    }

    public double getSignAmplifyProportion() {
        return signAmplifyProportion;
    }

    public void setSignAmplifyProportion(double signAmplifyProportion) {
        this.signAmplifyProportion = signAmplifyProportion;
    }

    private int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
